﻿using AutoMapper;
using AutoMapper.QueryableExtensions;

using Holla.Core.Application.ViewModels;
using Holla.Core.Domain.Entities;
using Holla.Core.Persistence;

using MediatR;

using Microsoft.EntityFrameworkCore;

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Holla.Core.Application.Queries
{
    public class TodoListQuery : IRequest<List<TodoViewModel>>
    {
        public TodoStatus? Status { get; set; }

        public class Handler : IRequestHandler<TodoListQuery, List<TodoViewModel>>
        {
            private readonly CoreDbContext _dbContext;
            private readonly IMapper _mapper;

            public Handler(CoreDbContext dbContext, IMapper mapper)
            {
                _dbContext = dbContext;
                _mapper = mapper;
            }

            public async Task<List<TodoViewModel>> Handle(TodoListQuery request, CancellationToken cancellationToken)
            {
                var query = _dbContext.Todos.AsQueryable();
                if (request.Status.HasValue)
                {
                    query = query.Where(p => p.Status == request.Status.Value);
                }

                return await query
                    .ProjectTo<TodoViewModel>(_mapper.ConfigurationProvider)
                    .OrderByDescending(p => p.LastUpdated)
                    .ToListAsync(cancellationToken: cancellationToken)
                    .ConfigureAwait(false);
            }
        }
    }
}

